var gulp = require('gulp');
var uglifyjs = require("gulp-uglify");
var uglifycss = require("gulp-minify-css");
var uglifyhtml = require("gulp-minify-html");
var uglifyimages = require("gulp-imagemin");
var jshint = require("gulp-jshint");
var concatjs = require("gulp-concat");
var renamejs = require("gulp-rename");
var lesscs = require("gulp-less");
var livereload = require("gulp-livereload");


// 代码检查
gulp.task("hintjs", function() {
	gulp.src("src/js/apps/*.js")
		.pipe(jshint())
		.pipe(jshint.reporter());
});

// JS -> 压缩、合并、重命名
gulp.task("finajs", function() {
	gulp.src("src/js/apps/*.js")
		.pipe(concatjs("app.js")) // 合并之后叫什么名字
		.pipe(uglifyjs())
		.pipe(renamejs({
			suffix: ".min"
		}))
		.pipe(gulp.dest("dist/js/apps"))
});

// CSS -> 压缩、合并、重名命
gulp.task("finacss", function() {
	gulp.src("src/css/*.css")
		.pipe(concatjs("index.css")) // 合并之后叫什么名字
		.pipe(uglifycss())
		.pipe(renamejs({
			suffix: ".min"
		}))
		.pipe(gulp.dest("dist/css"))
});

// 压缩HTML
gulp.task("htmluglify", function() {
	gulp.src("src/index.html")
		.pipe(uglifyhtml())
		.pipe(gulp.dest("dist"))
});

// 图片压缩
gulp.task("imageuglify", function() {
	gulp.src("src/images/*.{png,jpg,gif,ico,jpeg}")
		.pipe(uglifyimages({
			progressive: true, // 压缩无损图片
			multipass: true // 多次优化svg直到完全优化
		}))
		.pipe(gulp.dest("dist/images"))
});

// 监听
gulp.task("watch", function() {
	gulp.watch('src/index.html', function() {
		gulp.run('htmluglify');
	});
});

// 热更新
gulp.task("hot", function() {
	livereload.listen();
	gulp.watch('dist/index.html', function(event) {
		livereload.changed(event.path);
	});
});

gulp.task('default', function() {
	gulp.start(["htmluglify", "finajs", "finacss", "imageuglify"]);
});